<template>
  <div class="profile-page">
    <!-- 用户信息头部 -->
    <ProfileHeader 
      :user-info="currentUserInfo"
      :stats="userStats"
      @profile-updated="handleProfileUpdated"
    />

    <!-- 内容标签页 -->
    <div class="content-tabs">
      <div class="main-tabs">
        <div
            v-for="tab in mainTabs"
            :key="tab.id"
            :class="['tab-item', { active: activeMainTab === tab.id }]"
            @click="selectMainTab(tab.id)"
        >
          {{ tab.name }}
        </div>
      </div>
    </div>

    <!-- 内容区域 - 引入子组件 -->
    <div class="content-display">
      <!-- 根据选中的标签显示不同内容 -->
      <WorksContent
          v-if="activeMainTab === 'works'"
          type="works"
          @refresh="handleContentRefresh"
      />
      <!-- 合集内容 -->
      <CollectionsContent
          v-if="activeMainTab === 'collections'"
          type="collections"
          @refresh="handleContentRefresh"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/authStore'
// 引入作品内容子组件（假设文件名）
import WorksContent from '@/components/profile/WorksManager.vue'
import CollectionsContent from '@/components/profile/CollectionsManager.vue'
import ProfileHeader from "@/components/profile/ProfileHeader.vue";
import {getUser} from "@/api/user/sysUserController";

// Props
interface UserInfo {
  userId?: number
  name?: string
  avatar?: string
  username?: string
  nickname?: string
  email?: string
  sex?: number
  phone?: string
  filePath?: string
  douyinId?: string
}

interface Stats {
  following?: number
  followers?: number
  likes?: number
  liveCount?: number
}

interface Props {
  userInfo?: UserInfo
}

const props = withDefaults(defineProps<Props>(), {
  userInfo: () => ({})
})

const userStats = ref<Stats>({
  following: 330,
  followers: 5,
  likes: 0,
  liveCount: 7
})

const router = useRouter()
const authStore = useAuthStore()

// Emits - 可根据需要向更上层组件传递事件
const emit = defineEmits<{
  tabChange: [tabId: string]
  contentRefresh: []
}>()

// 用户信息
const currentUserInfo = ref<UserInfo>({})

// 获取用户信息
const loadUserInfo = async () => {
  try {
    const result = await getUser()
    if ((result as any).code === '00000' && result.data) {
      const userData = result.data as any
      currentUserInfo.value = {
        userId: userData.userId,
        username: userData.username,
        nickname: userData.nickname,
        email: userData.email,
        sex: userData.sex,
        phone: userData.phone,
        filePath: userData.filePath,
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 如果getUser接口失败，使用localStorage中的信息作为备用
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr)
      currentUserInfo.value = {
        userId: userInfo.userId ,
        username: userInfo.username,
        nickname: userInfo.nickname ,
        email: userInfo.email,
        sex: userInfo.sex,
        phone: userInfo.phone,
        filePath: userInfo.filePath ,
      }
    }
  }
}

// 处理资料更新
const handleProfileUpdated = (updatedUserInfo: UserInfo) => {
  currentUserInfo.value = { ...currentUserInfo.value, ...updatedUserInfo }
  // 这里可以触发父组件的更新
  console.log('用户资料已更新:', updatedUserInfo)
}

// 检查登录状态并加载用户信息
onMounted(async () => {
  if (!authStore.isLoggedIn) {
    router.push('/')
    return
  }
  await loadUserInfo()
})

// 简化标签数据 - 只保留作品和合集
const mainTabs = ref([
  { id: 'works', name: '作品' },
  { id: 'collections', name: '合集' }
])

// 当前选中的标签
const activeMainTab = ref('works')

// 标签切换方法
const selectMainTab = (tabId: string) => {
  activeMainTab.value = tabId
  // 向父组件（如果有）传递标签切换事件
  emit('tabChange', tabId)
}

// 处理内容刷新事件（从子组件接收）
const handleContentRefresh = () => {
  // 可以在这里更新标签计数等操作
  if (activeMainTab.value === 'works') {
    // 示例：更新作品数量（实际应从接口获取）
    mainTabs.value[0].name = `作品 ${Math.floor(Math.random() * 10)}`
  }
  // 向更上层组件传递刷新事件
  emit('contentRefresh')
}

// 其他交互方法
const handleEdit = () => {
  // 编辑资料逻辑
  console.log('编辑用户资料')
}

const handleStatClick = (type: string) => {
  // 统计项点击逻辑
  console.log('点击了统计项：', type)
}
</script>

<style scoped>
/* 样式部分保持不变 */
.profile-page {
  padding: 24px;
  background: rgba(15, 52, 96, 0.9);
  border-radius: 16px;
  box-shadow: 0 10px 35px rgba(0, 0, 0, 0.35);
  backdrop-filter: blur(12px);
  color: #fff;
  transition: all 0.3s ease;
}

/* 用户信息头部优化 */
.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  gap: 28px;
}

.profile-avatar {
  position: relative;
}

.avatar-img {
  border: 4px solid rgba(255, 255, 255, 0.1);
  transition: transform 0.3s ease;
}

.avatar-img:hover {
  transform: scale(1.05);
}

.profile-info {
  flex: 1;
  padding: 8px 0;
}

.profile-name {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.profile-name h2 {
  margin: 0;
  font-size: 26px;
  font-weight: 600;
  color: #fff;
  position: relative;
}

.profile-name h2::after {
  content: '';
  position: absolute;
  bottom: -4px;
  left: 0;
  width: 0;
  height: 2px;
  background: #ff4757;
  transition: width 0.3s ease;
}

.profile-name:hover h2::after {
  width: 100%;
}

.edit-icon {
  font-size: 20px;
  color: #ff4757;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 4px;
  border-radius: 50%;
}

.edit-icon:hover {
  background: rgba(255, 71, 87, 0.15);
  transform: rotate(90deg);
}

.profile-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
  font-size: 15px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #ddd;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.stat-item:hover {
  color: #ff4757;
  background: rgba(255, 255, 255, 0.05);
}

.live-indicator {
  color: #ff4757;
  font-weight: 500;
}

.live-dot {
  width: 10px;
  height: 10px;
  background-color: #ff4757;
  border-radius: 50%;
  position: relative;
}

/* 直播点呼吸动画 */
.pulse::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: rgba(255, 71, 87, 0.5);
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: translate(-50%, -50%) scale(0.8);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(2);
    opacity: 0;
  }
}

.profile-id {
  font-size: 14px;
  color: #aaa;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.profile-id::before {
  content: '🔗';
  font-size: 16px;
}

.profile-gender {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #aaa;
}

.gender-icon {
  font-size: 18px;
  color: #ff69b4;
}

/* 内容标签页优化 */
.content-tabs {
  display: flex;
  flex-direction: column;
  margin-bottom: 28px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.main-tabs {
  display: flex;
  gap: 28px;
  padding: 12px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  overflow-x: auto;
  scrollbar-width: none;
}

.main-tabs::-webkit-scrollbar {
  display: none;
}

/* 主标签样式 */
.main-tabs .tab-item {
  padding: 6px 0;
  font-size: 15px;
  color: #bbb;
  cursor: pointer;
  white-space: nowrap;
  position: relative;
  transition: color 0.3s ease;
}

.main-tabs .tab-item:hover {
  color: #fff;
}

.main-tabs .tab-item.active {
  color: #ff4757;
  font-weight: 500;
}

.main-tabs .tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background: #ff4757;
  border-radius: 3px;
}

/* 内容区域优化 */
.content-display {
  margin-top: 28px;
  min-height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>